import { tencentAK } from '../../common/const.js'
import { map } from '../../data/data';
import { myGetRequest, myPostRequest } from "../../utils/myRequest.js"
var consoleUtil = require('../../utils/consoleUtil.js');
var dateUtil = require('../../utils/dateUtil.js');
var mapService = require('../../service/mapService.js');
var QQMapWX = require('../../lib/qqmap-wx-jssdk.js');
let scenicList = require('../../data/data');
//index.js
//获取应用实例
const app = getApp();
const defaultScale = 14;

//定义全局变量
var totalMarker = [];
var curId = 1;
let includePointsData = [];
//ui相关
var bottomHeight = 0;
var windowHeight = 0;
var windowWidth = 0;
//Map组件
var mapId = 'myMap';
var qqmapsdk;
Page({
  data: {
    userInfo: {},
    showSignStart:true,
    //marker弹窗
    showDialog:false,
    scenicName:"",
    scenicIntroduction:"",
    Introduction:"",
    image:"",
    //默认坐标
    longitude: '120.414721',
    latitude: '36.072530',
    //地图缩放级别
    scale: defaultScale,
    markers: [],
    showUpload: true,
    //运动路线
    polyline: [],
    //发生给服务器的位置数据
    traceList: [],
    //地图高度
    mapHeight: 0,
    selectAddress: '',
    centerLongitude: '',
    centerLatitude: '',
    currentMarkerId: 0,

  },

  onLoad: function (options) {
    var that = this;
    console.log("页面初始化");
    var userInfo;
    try {
       userInfo = wx.getStorageSync('userInfo');
      if (!userInfo) {
        wx.redirectTo({
          url: '../login/login'
        })
      }
    } catch (e) {
      // Do something when catch error
      console.log("页面初始化失败： "+e)
    }
    that.setData({
      userInfo : userInfo
    })
    //检测更新
    mapService.checkUpdate();
    //定位权限校验
    mapService.scopeSetting(that);
  },

  onShow: function () {
    consoleUtil.log('onShow--------------------->');
    var that = this;
    that.changeMapHeight();
    //设置上传按钮的布局
    //如果刚从选择地址页面带数据回调回来，则显示选择的地址
    that.getCenterLocation();
    //请求地理位置信息,移动中心点坐标
    //mapService.requestLocation(that);
    that.queryMarkerInfo();
  },

  /**
   * 页面不可见时
   */
  onHide: function () {

  },
  //页面初始化时设置地图高度
  changeMapHeight: function () {
    var that = this;
    var count = 0;
    wx.getSystemInfo({
      success: function (res) {
        consoleUtil.log('页面初始化时设置地图高度' + res);
        windowHeight = res.windowHeight;
        windowWidth = res.windowWidth;

        that.setMapHeight();
      },
    })
  },

  setMapHeight: function (params) {
    var that = this;
    that.setData({
      mapHeight: (windowHeight - bottomHeight) + 'px'
    })

  },
  //--------------------UI设置end---------------------

  /** 
   * 初始化地图
   */
  initMap: function () {
    var that = this;
    qqmapsdk = new QQMapWX({
      key: tencentAK
    });
    that.getCenterLocation();
  },


  /**
   * 更新上传坐标点
   */
  updateCenterLocation: function (latitude, longitude) {
    var that = this;
    that.setData({
      centerLatitude: latitude,
      centerLongitude: longitude
    })
  },

  /**
   * 回到定位点
   */
  selfLocationClick: function () {
    var that = this;
    //还原默认缩放级别
    that.setData({
      scale: defaultScale
    })
    //必须请求定位，改变中心点坐标
    mapService.requestLocation(that);
  },

  /**
   * 移动到中心点
   */
  moveTolocation: function () {
    var mapCtx = wx.createMapContext(mapId);
    mapCtx.moveToLocation();
  },


  /**
   * 点击控件时触发
   */
  controlTap: function () {

  },

  /**
   * 点击地图时触发
   */
  bindMapTap: function () {
    //恢复到原始页
    this.adjustViewStatus(true);
  },

  adjustViewStatus: function (uploadStatus) {
    var that = this;
    that.setData({
      //显示marker
      //showDialog: uploadStatus,
    })
    that.changeMapHeight();
  },

  onShareAppMessage: function (res) {

  },

  /**
   * 拖动地图时回调
   * 视野发生变化时触发
   */
  regionChange: function (res) {
    var that = this;
    // 改变中心点位置  
    if (res.type == "end") {
      that.getCenterLocation();
    }
  },

  /**
   * 得到中心点坐标
   */
  getCenterLocation: function () {
    var that = this;
    var mapCtx = wx.createMapContext(mapId);
    mapCtx.getCenterLocation({
      success: function (res) {
        that.updateCenterLocation(res.latitude, res.longitude);
        //逆地址解析
        //mapService.regeocodingAddress(that,qqmapsdk);
        //that.queryMarkerInfo();
      }
    })
  },
  //-----------------------Marker相关处理逻辑------------------------
  /**
   * 查询 marker 信息
   * 初始化的时候调用
   */
  queryMarkerInfo: function () {
    var that = this;
    consoleUtil.log('查询当前坐标 marker 点信息')
    //调用请求 marker 点的接口就好了
    //--默认景点marker
    totalMarker=[];
    for (let item of scenicList) {
      let marker = that.createInitMarker(item);
      totalMarker.push(marker);
    }
    consoleUtil.log('-----------------------');
    consoleUtil.log('初始化marker' + totalMarker);
    that.setData({
      markers: totalMarker
    })
    var mapCtx1 = wx.createMapContext(mapId);
    // 显示所有标记点
  mapCtx1.includePoints({
  padding: [20],
  points: includePointsData //放入所有坐标轴的数组   并引用此方法
})
  },
  /**
   * 
   * 点击marker
   */
  bindMakertap: function (e) {
    var that = this;
    curId = e.markerId
    var name = this.data.markers[curId - 1].name
    console.log('点击了：Marker '+name);
    console.log(this.data.markers[curId - 1])
    //重新设置点击marker为中心点
      var marker = that.data.markers[curId - 1];
        that.setData({
          longitude: marker.longitude,
          latitude: marker.latitude,
          scenicIntroduction:marker.Introduction,
          scenicName:marker.name,
          image:marker.image,
          showDialog:true
         
        })
    
  },
  toggleDialog: function () {
    this.setData({
      showDialog: false,
    })
  },
  /**
   * 创建marker
   */
  createInitMarker: function (point) {
    let latitude = point.endLat;
    let longitude = point.endLong;

    includePointsData.push(
      {
        latitude: latitude,
        longitude:longitude
      }
    )
    let marker = {
      iconPath: point.iconUrl,
      id: point.id || 0,
      name: point.name || '',
      latitude: latitude,
      longitude: longitude,
      width: 30,
      height: 30,
      
                      //景点简介
                      Introduction: point.Introduction,
                      //景点路线
                      routeId: point.routeId,
                      //beginLat
                      beginLat: point.beginLat,
                      beginLong: point.beginLong,
                      //简介照片
                      image:point.image,
      label: {
        content: point.name,
        color: '#0081ff',
        fontSize: 8,
        bgColor: "#fff",
        borderRadius: 30,
        borderColor: "#0081ff",
        borderWidth: 1,
        padding: 3,
        textAlign:"center"
      },
      callout: {
        content: point.name,
        fontSize: 0,
      }
    };
    return marker;
  },
 
//-------------------------------------------------景点选择完毕进入打卡页面---------------
enterSignStart:function() {
  var that = this;
  //跳转到map，携带关键参数
  wx.redirectTo({
    url: "/pages/map/map?curMarker=" + JSON.stringify(that.data.markers[curId - 1]),
  })

},
enterTurnto:function() {
  var that=this;
  wx.showModal({
    title: '提示',
    content: '进入答题',
   async success(res) {
      if (res.confirm) {
        wx.navigateTo({
          url: '/pages/test/test?userid='+that.data.userInfo.id+'?routeId='+that.data.markers[curId - 1].routeId
        })
        // const list=  await myPostRequest({
        //   url:'/problem/findall',
        //   data:that.data,
         
        // })
        // console.log(list.data)

      } else if (res.cancel) {
        console.log('用户取消答题')
      }
    }
  })
}

})
